package Socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/*
聊天室的客户端

为了能够收发信息
 */
public class Client4 {
    private Socket socket;

    public Client4() {
        try {
            System.out.println("客户端开始运行");
            socket = new Socket("172.86.0.85", 8088);
            System.out.println("已经连接");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {

            //启动接收服务器的线程
            ServerHandler handler =new ServerHandler();
            Thread t=new Thread(handler);
            t.start();

            //发送消息给服务器
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw, true);


            Scanner sc = new Scanner(System.in);


                    while (true) {
                        //发送
                        String line;
                        line = sc.nextLine();
                        if ("exit".equals(line)) {
                            break;
                        }
                        pw.println(line);
                    }


        } catch (IOException e) {
//            e.printStackTrace();
        } finally {
            try {
                socket.close();  //与服务端断开
            } catch (IOException ioException) {
//                ioException.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client4 client = new Client4();
        client.start();
    }

    class ServerHandler implements Runnable{
        @Override
        public void run() {
            //接收信息

            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr=new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br=new BufferedReader(isr);

                String line;
                while((line=br.readLine())!=null){
                    System.out.println(line);
                }
            } catch (IOException e) {
//                e.printStackTrace();
            }

        }
    }

}
